﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MaxLeaf.DAL.Web2SCP;
using MaxLeaf.DB;
using System.Data;
using System.Data.SqlClient;
using MaxLeaf.Common;

namespace MaxLeaf.DAL.Web2SCP
{
    /// <summary>
    /// 分发基类,add/update/delete
    /// </summary>
    public class BaseDAL : IDALAction
    {


        public enum GetDataType
        {
            OrgData

        }
        //维护表名
        protected string strSCPTableName = null;
        protected string strWebTableName = null;

        protected string strWebMapKeyFieldName = string.Empty;
        protected string strWebMapKeyTableName = string.Empty;

        //实际数据库key
        protected string strSCPKeyFieldName = string.Empty;
        protected string strWebKeyFieldName = string.Empty;
        //维护的字段，不包括key
        protected string strFieldNames = null;
        //新增时是否填写key值
        protected bool mblnNeedEditKeyValue = true;
        //mapkey是不是自增长的
        protected bool mblnIsIdentity = false;
 

                /// <summary>
        /// 根据mapkey删除表数据
        /// 如果通过key找不到，表示不是通过程序分发的，忽略
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="dbDestSCPCon"></param>
        /// <param name="strKeyValue"></param>
        public virtual void Delete(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, string strKeyValue)
        {


        }


        /// <summary>
        /// Add没有单独处理,放在update
        /// 每次全部update
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="dbDestSCPCon"></param>
        /// <param name="strKeyValue"></param>
        public virtual int Add(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, string strKeyValue)
        {


            return Update(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, strKeyValue);

        }
        
        /// <summary>
        /// 每次全部update
        /// </summary>
        /// <param name="dbOrgWebReadCon">来源数据库</param>
        /// <param name="dbDestSCPCon">目标数据库</param>
        /// <param name="strKeyValue"></param>
        public virtual int Update(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, string strKeyValue)
        {
            KeyValuePair<string, IDataParameter[]> kvpParam;
            string strWebOrgKeyValue = strKeyValue;
            string strUpdateFieldName = strFieldNames;

            
            string strSCPDestKeyValue = strKeyValue;
 

            kvpParam = CreateKeyParaCond(dbDestSCPCon, strSCPKeyFieldName, strSCPDestKeyValue, true);

            DataTable dtData = dbDestSCPCon.GetDataTable(
                string.Format("select {0} from {1} where {2}"
                        , strSCPKeyFieldName + "," + strUpdateFieldName
                        , strSCPTableName
                        , kvpParam.Key
                        )
                , kvpParam.Value
                );
            DataRow drData = null;
            LogStatus logStatus = LogStatus.Update;

            DataTable dtOrgData = DAL_GetData(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, (int)GetDataType.OrgData, strWebOrgKeyValue);
            if (dtOrgData == null || dtOrgData.Rows.Count == 0)
            {
                return 0;
            }
            DataRow drOrgData = dtOrgData.Rows[0];


            const string TMPDESTKEYVALUE = "-987654321";
            if (dtData.Rows.Count == 0)
            {
                //add
                strSCPDestKeyValue = TMPDESTKEYVALUE;

                logStatus = LogStatus.Add;
                drData = dtData.NewRow();
                if (mblnNeedEditKeyValue)
                {
                    DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon,strSCPKeyFieldName, drOrgData, drData);

                    if ((strUpdateFieldName + ",").IndexOf(strSCPKeyFieldName + ",", StringComparison.InvariantCultureIgnoreCase) < 0)
                    {
                        strUpdateFieldName = strSCPKeyFieldName + "," + strUpdateFieldName;
                    }
                }


               
            }
            else
            {
                drData = dtData.Rows[0];
            }

            //其他字段填值
            string[] arrFieldName = strUpdateFieldName.Split(',');
            foreach (string strField in arrFieldName)
            {
                DAL_GetFieldData(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, strField, drOrgData, drData);
            }

            Update_Before(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, drOrgData, drData);

            //add or update
            KeyValuePair<string, IDataParameter[]> kvp = dbDestSCPCon.CreateParamSql(strUpdateFieldName, strSCPTableName, drData, logStatus, strSCPKeyFieldName);
            string strIdentity = dbDestSCPCon.GetValue(kvp.Key, kvp.Value);
            if (mblnIsIdentity && logStatus == LogStatus.Add)
            {
                drData[strSCPKeyFieldName] = strIdentity;
            }
            if (strSCPDestKeyValue.Equals(TMPDESTKEYVALUE))
            {

                 
                    strSCPDestKeyValue = CvtFunc.ToString(drData[strSCPKeyFieldName]);
                
                SaveKeyMap(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, strWebOrgKeyValue, strSCPDestKeyValue);

            }

             

            UpdateOtherData(dbOrgWebReadCon, dbOrgWebWriteCon, dbDestSCPCon, drOrgData, drData);

            return CvtFunc.ToInt(drData[strSCPKeyFieldName]);

        }
         

        protected virtual void Update_Before(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, DataRow drOrgData, DataRow drData)
        {
            
        }

        protected virtual void SaveKeyMap(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, string strOrgKeyValue, string strDestKeyValue)
        {
            if (!string.IsNullOrEmpty(strWebMapKeyTableName))
            {
                WebKeyMapDict map = new WebKeyMapDict
                {
                    TableName = strWebMapKeyTableName
                    ,
                    WebMapKeyFieldName = strWebMapKeyFieldName
                    ,
                    K3MapKeyFieldName = strSCPKeyFieldName
                    ,
                    WebKeyValue = strOrgKeyValue
                    ,
                    K3KeyValue = strDestKeyValue
                };

                SaveSCPWebKeyMap(dbDestSCPCon, map);

                
                    dbOrgWebWriteCon.WebKeyMap.Add(map);
             
            }

            
        }

        private void SaveSCPWebKeyMap(DBAccess dbDestSCPCon, WebKeyMapDict map)
        {
//            string strSql = @"if exists(select * from  mWebSCPKeyMap where TableName=@TableName and WebKeyValue=@WebKeyValue)
//                begin
//                    update mWebSCPKeyMap  set  SCPKeyValue=@SCPKeyValue  where TableName=@TableName and WebKeyValue=@WebKeyValue and not SCPKeyValue=@SCPKeyValue
//                end
//            else
//                begin
//                    insert into mWebSCPKeyMap(TableName,WebKeyValue,SCPKeyValue) values(@TableName,@WebKeyValue,@SCPKeyValue)
//                end
//            ";
//            dbDestSCPCon.ExecuteSql(strSql, new SqlParameter[] { 
//                new SqlParameter("@TableName",map.TableName)
//                ,new SqlParameter("@WebKeyValue",map.WebKeyValue)
//                ,new SqlParameter("@SCPKeyValue",map.SCPKeyValue)
//            });
        }



      

        /// <summary>
        /// 更新完主数据，再更新其他数据
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="dbDestSCPCon"></param>
        /// <param name="drOrgData"></param>
        /// <param name="drData"></param>
        protected virtual void UpdateOtherData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, DataRow drOrgData, DataRow drData)
        {

        }
 
        /// <summary>
        /// 根据FielName赋值
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="dbDestSCPCon"></param>
        /// <param name="strFieldName"></param>
        /// <param name="drOrgData"></param>
        /// <param name="drDestData"></param>
        protected virtual void DAL_GetFieldData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, string strSCPFieldName, DataRow drOrgData, DataRow drDestData)
        {
            if (strSCPFieldName.Equals(strSCPKeyFieldName, StringComparison.InvariantCultureIgnoreCase))
            {
                drDestData[strSCPFieldName] = drOrgData[strWebKeyFieldName];
            }
            else
            {
                drDestData[strSCPFieldName] = drOrgData[strSCPFieldName];
            }
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="dbDestSCPCon"></param>
        /// <param name="intdataType"></param>
        /// <param name="objParam"></param>
        /// <returns></returns>
        protected virtual DataTable DAL_GetData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, DBAccess dbDestSCPCon, int intdataType, object objParam)
        {

            GetDataType dataType = (GetDataType)intdataType;
            if (dataType == GetDataType.OrgData)
            {
                return GetOrgData(dbOrgWebReadCon, dbOrgWebWriteCon, CvtFunc.ToString(objParam));
            }


            throw new MaxLeafException(string.Format("GetData {0} 没注册", intdataType));

        }

        /// <summary>
        /// 获取来源表数据
        /// </summary>
        /// <param name="dbOrgWebReadCon"></param>
        /// <param name="strOrgKeyValue"></param>
        /// <returns></returns>
        private DataTable GetOrgData(DBAccess dbOrgWebReadCon, DBAccess dbOrgWebWriteCon, string strWebKeyValue)
        {

            KeyValuePair<string, IDataParameter[]> kvpParam = CreateKeyParaCond(dbOrgWebReadCon, strWebKeyFieldName, strWebKeyValue, false);

            DataTable dtOrgData = dbOrgWebReadCon.GetDataTable(
             string.Format("select {0} from {1} where {2}"
             ,(strWebTableName.Equals("user_contract_goods")? strSCPKeyFieldName + "," + strFieldNames.Replace(",type,", ",0+type as type,") :"*")
                     , strWebTableName
                     , kvpParam.Key
                     )
             , kvpParam.Value
             );


            return dtOrgData;
        }

        /// <summary>
        /// 根据主key+辅助key建条件
        /// </summary>
        /// <param name="dbDestK3Con"></param>
        /// <param name="strKeyFieldName"></param>
        /// <param name="strDestKeyValue"></param>
        /// <param name="blnDest"></param>
        /// <returns></returns>
        private KeyValuePair<string, IDataParameter[]> CreateKeyParaCond(DBAccess dbDestK3Con, string strKeyFieldName, string strDestKeyValue, bool blnDest)
        {
            Dictionary<string, object> dictCond = new Dictionary<string, object>() { { strKeyFieldName, strDestKeyValue } };
             
            KeyValuePair<string, IDataParameter[]> kvp = dbDestK3Con.CreateCondParam(dictCond);
            return kvp;
        }
          
    }
}
